import requests

from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType  # noqa

# 下面的 token 全都过期了
# TOKEN = "pat_BpQRn0LEWYZMmcb8teFpaCOHqp01UtOM6zHhhRBKy9G4c7r7z8RmstKXoAJuvG3Y"
# TOKEN = "pat_OKhkPUe0kZFESsYiKjIeggrA30MuXjYvawBZ163fzjHVLnC3tVKVtRUcCXjSa4Q2" 
# TOKEN = "pat_84Uq0NNDhevxItN4HMxPdk0uu73L6qY4k4BXHa9HJETy5a1I8jN0QcZi9DAwfoRX"
# TOKEN = "pat_fFQAViNLD0Ochfgr91Ko9qaKmzj6NnXWs9GEYIGzoFp3UzJdRzS6SJTASIGwUlHM"

TOKEN = "sat_bLF9J7Vziicgya22Qe2k9V1Ylkd6oZkAcNesw2jLe62izArO4PJNUngownYIWZLq"

from cozepy import COZE_CN_BASE_URL


class CozeAgent():


    def __init__(self):
        #智能体id
        self.bot_id = "7485202131185123340"
        self.user_id = '001'
        self.headers = {
            "Authorization": f"Bearer {TOKEN}"
        }


    def chat(self):
        # 第一步 创建会话
        conversion_id = self.create_conversion_id()
        # 第二步 聊天，流式输出
        self.do_chat(conversion_id,"湖州吴兴AI+知识产权服务业集聚区建设情况")


    def create_conversion_id(self):
        url = COZE_CN_BASE_URL + "/v1/conversation/create"

        response = requests.post(url, headers=self.headers)
        if response.status_code == 200:
            data = response.json()
            print(data)
            return data["data"]["id"]
        else:
            print(f"Error: {response.status_code}")
            return None
        

    # 第二步 聊天，流式输出
    def do_chat(self,conversion_id,message):

        coze_api_token = TOKEN
        coze_api_base = COZE_CN_BASE_URL


        # Init the Coze client through the access_token.
        coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)


        for event in coze.chat.stream(
                bot_id=self.bot_id,
                user_id=self.user_id,
                conversion_id=conversion_id,
                additional_messages=[
                    Message.build_user_question_text(message),
                ],
        ):
            if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
                print(event.message.content, end="", flush=True)

            if event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
                print()
                print("token usage:", event.chat.usage.token_count)




if __name__ == '__main__':
    coze_agent = CozeAgent()
    coze_agent.chat()


    